//
//  AllScreenEditContentController.m
//  万物记
//
//  Created by Ajen on 2019/6/17.
//  Copyright © 2019 Ajen. All rights reserved.
//

#import "AllScreenEditContentController.h"
#import "BRPickerView.h"
#import "KeyboardWordsToolView.h"
#import "SetLocalWordsController.h"
@interface AllScreenEditContentController ()<UITextViewDelegate>{
    CGFloat keyboardHeight;
    UIButton *wordsBtn;
}
@property (weak, nonatomic) IBOutlet UITextView *inputView;
@property(nonatomic,strong)UIToolbar * myToolbar;
@property(nonatomic)KeyboardWordsToolView * wordsToolView;
@property(nonatomic)UIVisualEffectView *effectView;
@end

@implementation AllScreenEditContentController
-(void)viewWillDisappear:(BOOL)animated{
    if(self.endEditBlock){
        self.endEditBlock(self.inputView.text);
    }
    [super viewWillDisappear:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    UILabel * titleLabel = [UILabel new];
    titleLabel.aj_Text(@"编辑").aj_textColorHexStr(@"#2d2e36").aj_addToView(self.view);
    titleLabel.font = SongKeFont(23);
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(20);
        make.top.equalTo(self.view).offset(STATUS_BAR_HEIGHT);
        make.height.equalTo(@44);
    }];
    self.navigationItem.titleView = titleLabel;
    
    self.inputView.inputAccessoryView = self.myToolbar;
    self.inputView.text = self.editString;
    self.inputView.delegate = self;
    [self.inputView removeFromSuperview];
    [self.view addSubview:self.inputView];
    [self.inputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(self.view).offset(20);
        make.right.bottom.equalTo(self.view).offset(-20);
    }];
//    [self.inputView becomeFirstResponder];
    
}
- (void)textViewDidChange:(UITextView *)textView{
    if (self.inputView.markedTextRange == nil && textView.text.length > 5000) {
        [self.inputView resignFirstResponder];
        [self showMsg:@"主人~ 太长了,已经5000字了~"];
        self.inputView.text = [self.inputView.text substringToIndex:5000];
    }
}

- (UIToolbar *)myToolbar
{
    if (_myToolbar == nil) {
        CGRect tempFrame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44);
        _myToolbar = [[UIToolbar alloc] initWithFrame:tempFrame];
        
        
        UIButton *clearBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [clearBtn setTitle:@"清空      " forState:UIControlStateNormal];
        clearBtn.aj_buttonFont([UIFont systemFontOfSize:14 weight:UIFontWeightMedium]).aj_buttonTintColor([UIColor colorWithAjenHex:0x7A7374 alpha:0.5]);
        [clearBtn setFrame:CGRectMake(0, 0, 30, 30)];
        [clearBtn addTarget:self action:@selector(clearButtonDown) forControlEvents:UIControlEventTouchUpInside ];
        UIBarButtonItem *clearItem = [[UIBarButtonItem alloc]initWithCustomView:clearBtn];
        
        wordsBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [wordsBtn setTitle:@"   词条   " forState:UIControlStateNormal];
        wordsBtn.aj_buttonFont([UIFont systemFontOfSize:13 weight:UIFontWeightMedium]).aj_buttonTintColor([UIColor colorWithAjenHex:0x7A7374 alpha:0.5]);
        [wordsBtn setFrame:CGRectMake(0, 0, 30, 30)];
        wordsBtn.tag = 100;
        [wordsBtn addTarget:self action:@selector(wordsButtonDown) forControlEvents:UIControlEventTouchUpInside ];
        UIBarButtonItem *wordsItem = [[UIBarButtonItem alloc]initWithCustomView:wordsBtn];
        
        UIButton *timeBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [timeBtn setTitle:@"   插入时间   " forState:UIControlStateNormal];
        timeBtn.aj_buttonFont([UIFont systemFontOfSize:13 weight:UIFontWeightMedium]).aj_buttonTintColor([UIColor colorWithAjenHex:0x7A7374 alpha:0.5]);
        [timeBtn setFrame:CGRectMake(0, 0, 30, 30)];
        [timeBtn addTarget:self action:@selector(timeButtonDown) forControlEvents:UIControlEventTouchUpInside ];
        UIBarButtonItem *timeItem = [[UIBarButtonItem alloc]initWithCustomView:timeBtn];
        
        UIButton *copyBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [copyBtn setTitle:@"   复制全部   " forState:UIControlStateNormal];
        copyBtn.aj_buttonFont([UIFont systemFontOfSize:13 weight:UIFontWeightMedium]).aj_buttonTintColor([UIColor colorWithAjenHex:0x7A7374 alpha:0.5]);
        [copyBtn setFrame:CGRectMake(0, 0, 30, 30)];
        [copyBtn addTarget:self action:@selector(copyButtonDown) forControlEvents:UIControlEventTouchUpInside ];
        UIBarButtonItem *copyItem = [[UIBarButtonItem alloc]initWithCustomView:copyBtn];
        
        UIButton *pasteBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [pasteBtn setTitle:@"   粘贴   " forState:UIControlStateNormal];
        pasteBtn.aj_buttonFont([UIFont systemFontOfSize:13 weight:UIFontWeightMedium]).aj_buttonTintColor([UIColor colorWithAjenHex:0x7A7374 alpha:0.5]);
        [pasteBtn setFrame:CGRectMake(0, 0, 30, 30)];
        [pasteBtn addTarget:self action:@selector(pasteButtonDown) forControlEvents:UIControlEventTouchUpInside ];
        UIBarButtonItem *pasteItem = [[UIBarButtonItem alloc]initWithCustomView:pasteBtn];
        
        
        UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [closeBtn setTitle:@"       完成" forState:UIControlStateNormal];
        closeBtn.aj_buttonFont([UIFont systemFontOfSize:15 weight:UIFontWeightBold]).aj_buttonTintColor([UIColor colorWithAjenHex:0x7A7374 alpha:1]);
        [closeBtn setFrame:CGRectMake(0, 0, 30, 30)];
        [closeBtn addTarget:self action:@selector(closeButtonDown) forControlEvents:UIControlEventTouchUpInside ];
        UIBarButtonItem *closeItem = [[UIBarButtonItem alloc]initWithCustomView:closeBtn];
        
        _myToolbar.items = @[clearItem,wordsItem,timeItem,copyItem,pasteItem,closeItem];
    }
    
    return _myToolbar;
}

-(void)clearButtonDown{
    if(!self.inputView.text.length){
        return;
    }
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否清空当前输入框内所有内容?" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"清空" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.inputView.text = @"";
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

-(void)wordsButtonDown{
    if(wordsBtn.tag == 100){
        wordsBtn.tag = 200;
        [wordsBtn setTitle:@"   收回   " forState:UIControlStateNormal];
        self.effectView.frame = CGRectMake(0, self.view.Height - keyboardHeight - 44, SCREEN_WIDTH, 44);
        [self.view addSubview:self.effectView];
        self.wordsToolView.frame = CGRectMake(0, self.view.Height - keyboardHeight - 44, SCREEN_WIDTH, 44);
        [self.view addSubview:self.wordsToolView];
        WeakObj(self);
        self.wordsToolView.singleWordBlock = ^(NSString * _Nonnull wordString) {
            
            NSInteger positionIndex = weak_self.inputView.selectedRange.location;
            NSMutableString * muString = [NSMutableString stringWithCapacity:0];
            [muString appendString:weak_self.inputView.text];
            [muString insertString:wordString atIndex:positionIndex];
            weak_self.inputView.text = muString;
            [weak_self.inputView setSelectedRange:NSMakeRange(positionIndex + wordString.length, 0)];
        };
        self.wordsToolView.setWordsBlock = ^{
            wordsBtn.tag = 100;
            [wordsBtn setTitle:@"   词条   " forState:UIControlStateNormal];
            [self.effectView removeFromSuperview];
            [self.wordsToolView removeFromSuperview];
            
            [weak_self.inputView resignFirstResponder];
            SetLocalWordsController * setWordsController = [SetLocalWordsController new];
            [weak_self.navigationController pushViewController:setWordsController animated:YES];
        };
    }else{
        wordsBtn.tag = 100;
        [wordsBtn setTitle:@"   词条   " forState:UIControlStateNormal];
        [self.effectView removeFromSuperview];
        [self.wordsToolView removeFromSuperview];
    }
    
}

-(void)timeButtonDown{
    NSInteger positionIndex = self.inputView.selectedRange.location;
    [self closeButtonDown];
    [BRDatePickerView showDatePickerWithTitle:@"" dateType:BRDatePickerModeYMDHM defaultSelValue:nil minDate:nil maxDate:nil isAutoSelect:NO themeColor:nil resultBlock:^(NSString *selectValue) {
        [self.inputView becomeFirstResponder];
        NSMutableString * muString = [NSMutableString stringWithCapacity:0];
        [muString appendString:self.inputView.text];
        [muString insertString:selectValue atIndex:positionIndex];
        self.inputView.text = muString;
        [self.inputView setSelectedRange:NSMakeRange(positionIndex + selectValue.length, 0)];
    } cancelBlock:^{
        [self.inputView becomeFirstResponder];
        [self.inputView setSelectedRange:NSMakeRange(positionIndex, 0)];
    }];
}
-(void)copyButtonDown{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    [pasteboard setString:self.inputView.text];
}
-(void)pasteButtonDown{
    NSString *content = [[UIPasteboard generalPasteboard] string];
    
    self.inputView.text = [NSString stringWithFormat:@"%@%@",self.inputView.text,content];
}
-(void)closeButtonDown{
    
    [self.inputView resignFirstResponder];
}











-(UIVisualEffectView *)effectView{
    if(!_effectView){
        UIBlurEffect *effect = [UIBlurEffect effectWithStyle:0];
        _effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
    }
    return _effectView;
    
}

-(KeyboardWordsToolView *)wordsToolView{
    if(!_wordsToolView){
        _wordsToolView = [KeyboardWordsToolView new];
    }
    return _wordsToolView;
}

- (void)keyboardFrameChange:(NSNotification *)notifi{
    
    NSDictionary *userInfo = notifi.userInfo;
    CGRect endFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGRect beginFrame = [userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve curve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
    
    void(^animations)(void) = ^{
        [self willShowKeyboardFromFrame:beginFrame toFrame:endFrame];
    };
    
    void(^completion)(BOOL) = ^(BOOL finished){
        
    };
    
    [UIView animateWithDuration:duration delay:0.0f options:(curve << 16 | UIViewAnimationOptionBeginFromCurrentState) animations:animations completion:completion];
    
}

- (void)willShowKeyboardFromFrame:(CGRect)beginFrame toFrame:(CGRect)toFrame
{
    if (toFrame.origin.y  == [[UIScreen mainScreen] bounds].size.height){//键盘收起
        wordsBtn.tag = 100;
        [wordsBtn setTitle:@"   词条   " forState:UIControlStateNormal];
        [self.effectView removeFromSuperview];
        [self.wordsToolView removeFromSuperview];
        [self.inputView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.top.equalTo(self.view).offset(20);
            make.right.bottom.equalTo(self.view).offset(-20);
        }];
    }else{ //键盘升起
        keyboardHeight = toFrame.size.height;
        
        [self.inputView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.top.equalTo(self.view).offset(20);
            make.right.equalTo(self.view).offset(-20);
            make.bottom.equalTo(self.view).offset(-(keyboardHeight + 20 + 44));
        }];
        
        [UIView animateWithDuration:0.3 animations:^{
            [self.view layoutIfNeeded];
        }];
        
    }
}
@end
